package listeners;

import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Stack;

public class TestLEvaluator {
    // calculator
    public static class Evaluator extends LExprBaseListener {
        Stack<Integer> stack = new Stack<>();

        @Override
        public void exitMult(LExprParser.MultContext ctx) {
            int right = stack.pop();
            int left = stack.pop();
            stack.push(left * right);
        }

        @Override
        public void exitAdd(LExprParser.AddContext ctx) {
            int right = stack.pop();
            int left = stack.pop();
            stack.push(left + right);
        }

        @Override
        public void exitInt(LExprParser.IntContext ctx) {
            // terminal node
            stack.push(Integer.parseInt(ctx.INT().getText()));
        }
    }

    public static void main(String[] args) throws IOException {
        String inputFile = null;
        if (args.length>0) {
            inputFile = args[0];
        }
        InputStream is = System.in;
        if (inputFile != null) {
            is = new FileInputStream(inputFile);
        }
        CharStream input = CharStreams.fromStream(is);
        LExprLexer lexer = new LExprLexer(input);
        CommonTokenStream tokenStream = new CommonTokenStream(lexer);
        LExprParser parser = new LExprParser(tokenStream);
        parser.setBuildParseTree(true);
        ParseTree tree = parser.s();
        // show tree in text form
        System.out.println(tree.toStringTree(parser));
        ParseTreeWalker walker = new ParseTreeWalker();
        Evaluator evaluator = new Evaluator();
        walker.walk(evaluator, tree);

        System.out.println("stack result = " + evaluator.stack.pop());
    }

}
